package com.security;

import java.io.InputStream;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.content.Context;
import android.util.Log;

public class ResSecurity {

	public static byte[] decrypt(Context context, byte[] date)
			throws IllegalBlockSizeException, BadPaddingException {

		Cipher c1 = getCipher(Cipher.DECRYPT_MODE, context);
		Log.d("ResSecurity", "Cipher=" + c1);
		// 4 ִ�н���
		byte[] cipherByte = c1.doFinal(date);

		return cipherByte;
	}

	private static Cipher getCipher(int mode, Context context) {

		SecureRandom sr = new SecureRandom();
		// ����Կ�ļ��л�ȡԭʼ��Կ���
		byte[] rawKeyData = null;

		InputStream fileInputStream;
		try {
			fileInputStream = context.getAssets().open("icon.apk");
			rawKeyData = new byte[fileInputStream.available()];
			System.out.println(rawKeyData.length);
			fileInputStream.read(rawKeyData);
			fileInputStream.close();

			for (int i = 0; i < rawKeyData.length - 1; i += 2) {
				byte tmp = rawKeyData[i + 1];
				rawKeyData[i + 1] = rawKeyData[i];
				rawKeyData[i] = tmp;
			}

			// ����һ��DESKeySpec����
			DESKeySpec dks = new DESKeySpec(rawKeyData);
			// ����һ����Կ������Ȼ�������DESKeySpec����ת����Secret Key����
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(dks);
			// Cipher����ʵ����ɽ��ܲ���
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(mode, key, sr);
			return cipher;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
